<template>
  <div id="app">
    <!-- 头部导航 -->
    <header class="header">
      <div class="logo-container">
        <img src="../../assets/images/logo/logo.jpg" alt="宠物领养平台Logo" class="logo">
      </div>

      <!-- 导航菜单 -->
      <nav class="dropdown-container">
        <ul class="main-nav">
          <li @click="toggleMenu" class="menu-item">
            全部
            <span :class="['arrow', { 'rotate': isMenuVisible }]">▾</span>
          </li>
          <li class="search-item">
            <!-- 添加搜索类型选择 -->
            <div class="search-type-selector">
              <span :class="{ 'active': searchType === 'post' }" @click="searchType = 'post'">
                找贴
              </span>
              <span :class="{ 'active': searchType === 'user' }" @click="searchType = 'user'">
                找人
              </span>
            </div>
            <input type="text" v-model="searchQuery" placeholder="请输入搜索内容" @keydown.enter="performSearch">
            <button @click="performSearch">搜索</button>
          </li>
        </ul>

        <!-- 下拉菜单 -->
        <div class="dropdown-wrapper" v-if="isMenuVisible">
          <ul class="dropdown-menu">
            <li v-for="(item, key) in dropdownItems" :key="key" :class="key" @mouseover="showDropdown(key)"
              @mouseout="hideDropdown(key)">
              <a href="#">{{ item.label }}</a>
            </li>
          </ul>

          <!-- 二级下拉菜单 -->
          <template v-for="(item, key) in dropdownItems" :key="key">
            <ul :class="['submenu', key, { 'show': showDropdowns[key] }]" @mouseover="showDropdown(key)"
              @mouseout="hideDropdown(key)">
              <li v-for="(subItem, index) in item.subItems" :key="index">
                <router-link :to="subItem.route" class="menu-link">
                  {{ subItem.label }}
                </router-link>
              </li>
            </ul>
          </template>
        </div>
      </nav>

      <!-- 用户区域 -->
      <div class="user-area">
        <div class="avatar-icon-container" @click="handleIconClick">
          <el-icon color="#7c2d12" :size="24">
            <UserFilled />
          </el-icon>
          <!-- 好友请求红点提示 -->
          <span v-if="hasNewFriendRequests" class="notification-badge">●</span>
        </div>

        <div class="user-info" v-if="isLoggedIn">
          <div class="avatar">
            <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="用户头像">
          </div>
          <div class="user-name" @click="toggleUserMenu">
            <span>{{ userInfo.nickname }}</span>
            <span class="dropdown-arrow">▾</span>
          </div>

          <!-- 用户菜单 -->
          <ul class="user-menu" :class="{ 'show': isUserMenuVisible }">
            <li><router-link to="/update">修改个人信息</router-link></li>
            <li><a @click="handleLogout">退出！</a></li>
          </ul>
        </div>

        <div class="post-button">
          <button><router-link to="/contact">发布帖子</router-link></button>
        </div>
      </div>
    </header>

    <!-- 聊天面板 -->
    <div v-if="isChatPanelVisible" class="chat-panel-overlay" @click="closeChatPanel">
      <div class="chat-panel" @click.stop>
        <div class="chat-header">
          <div class="header-left">
            <span class="back-icon" @click="closeChatPanel">←</span>
            <span class="header-title">好友</span>
            <!-- 新增：好友请求按钮 -->
            <button class="friend-request-btn" @click.stop="toggleFriendRequests"
              :class="{ 'has-requests': hasNewFriendRequests }">
              好友请求
              <span v-if="hasNewFriendRequests" class="request-count">{{ newFriendRequests.length }}</span>
            </button>
          </div>

          <!-- 连接状态 -->
          <div :class="statusClass" class="status-indicator">
            <i :class="statusIcon"></i>
            <span>{{ statusText }}</span>
          </div>
        </div>

        <!-- 好友请求面板 -->
        <div v-if="isFriendRequestsVisible" class="friend-requests-panel">
          <div class="requests-header">
            <h3>新的好友请求</h3>
            <button class="close-btn" @click="toggleFriendRequests">×</button>
          </div>

          <div class="requests-list" v-if="newFriendRequests.length > 0">
            <div v-for="request in newFriendRequests" :key="request.id" class="request-item">
              <div class="request-avatar">
                <img :src="request.avatar || 'https://picsum.photos/id/1005/200/200'" :alt="request.nickname">
              </div>
              <div class="request-info">
                <div class="request-name">{{ request.nickname }}</div>
                <div class="request-account">账号: {{ request.account }}</div>
                <div class="request-phone" v-if="request.phone">电话: {{ request.phone }}</div>
              </div>
              <div class="request-actions">
                <button class="accept-btn" @click="handleFriendRequest(request.id, true)">接受</button>
                <button class="reject-btn" @click="handleFriendRequest(request.id, false)">拒绝</button>
              </div>
            </div>
          </div>

          <div class="no-requests" v-else>
            暂无新的好友请求
          </div>
        </div>

        <div class="chat-main" v-else>
          <!-- 左侧好友列表 -->
          <div class="friend-list">
            <div class="search-box">
              <input type="text" placeholder="搜索" class="search-input" v-model="friendSearchQuery"
                @input="filterFriends">
            </div>

            <div class="friend-items">
              <div v-for="friend in filteredFriends" :key="friend.id"
                :class="['friend-item', { 'active': currentFriend?.id === friend.id }]" @click="selectFriend(friend)">
                <div class="friend-avatar">
                  <img :src="friend.avatar" :alt="friend.nickname">
                  <span v-if="friend.unread" class="unread-badge">{{ friend.unread }}</span>
                </div>
                <div class="friend-info">
                  <div class="friend-name">{{ friend.nickname }}</div>
                  <div class="friend-last-message">{{ friend.lastMessage }}</div>
                </div>
                <div class="friend-time">{{ friend.lastTime }}</div>
                <!-- 删除好友按钮 -->
                <button class="delete-friend-btn" @click.stop="deleteFriend(friend.id)" title="删除好友">
                  <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24"
                    stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                      d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                  </svg>
                </button>
              </div>
            </div>
          </div>

          <!-- 右侧聊天内容 -->
          <div class="chat-content" v-if="currentFriend">
            <div class="chat-header-info">
              <div class="current-friend">
                <span class="friend-name">{{ currentFriend.nickname }}</span>
              </div>
            </div>

            <div class="chat-messages" ref="messagesContainer">
              <div v-for="(message, index) in currentFriend.messages" :key="index"
                :class="['message-item', message.isUser ? 'user-message' : 'friend-message']">
                <div class="message-avatar">
                  <img :src="message.isUser ? userAvatar : currentFriend.avatar" alt="头像">
                </div>
                <div class="message-content">
                  <div class="message-text">{{ message.text }}</div>
                  <div class="message-time">{{ message.time }}</div>
                </div>
              </div>
            </div>

            <div class="chat-input-area">
              <div class="input-box">
                <textarea v-model="newMessage" placeholder="输入消息..." @keydown.enter.prevent="sendMessage"
                  rows="3"></textarea>
                <button class="send-btn" @click="sendMessage" :disabled="!newMessage.trim() || !isWebSocketConnected">
                  发送
                </button>
              </div>
            </div>
          </div>

          <div class="no-selection" v-else>
            选择好友开始聊天
          </div>
        </div>
      </div>
    </div>

    <!-- 轮播图 -->
    <div class="carousel">
      <div class="carousel-inner" :style="{ transform: `translateX(${currentSlide * -100}%)` }"
        @transitionend="handleTransitionEnd">
        <div class="carousel-item" v-for="(slide, index) in extendedSlides" :key="index">
          <img :src="slide" :alt="`轮播图 ${index + 1}`">
        </div>
      </div>
      <div class="carousel-caption">
        <h1>遇见您生命中的新家人</h1>
        <p>从全球14,500多家爱心救助机构中发现您的完美伴侣</p>
      </div>
    </div>

    <div class="divider"></div>

    <!-- 信息图标区 -->
    <div class="info-icons">
      <div class="icon-item p-1" title="领养流程"></div>
      <div class="icon-item p-2" title="宠物护理"></div>
      <div class="icon-item p-3" title="成功故事"></div>
    </div>

    <!-- 宠物卡片区 -->
    <div class="card-section">
      <div class="section-title">
        <h1>Pets waiting for a new home</h1>
        <h2>等待新家的宠物</h2>
      </div>
      <div class="card-container">
        <CardGrid :cards="cardsData" />
      </div>
    </div>

    <!-- 文章区域 -->
    <div class="articles-section">
      <div class="article-card dog-article">
        <div class="article-image">
          <div class="article-text">
            小猫软乎乎的身子裹着绒毛，总用圆眼睛好奇打量世界。喂粮要定时定量，换猫砂别嫌麻烦，它们爱干净也怕孤单。有空多陪它玩逗猫棒，夜里别让它独自待在寒冷角落。生病时及时送医，别随意丢弃。每只小猫都是小生命，用耐心与温柔待它，它会用呼噜声和蹭手，还你满世界的治愈。
          </div>
        </div>
        <a href="#" class="read-more">READ MORE 阅读更多</a>
      </div>
      <div class="article-card cat-article">
        <div class="article-image">
          <div class="article-text">
            蜷缩的小身体藏着温暖的灵魂，湿漉漉的鼻尖总在探索世界。小狗用一生陪伴换你片刻温柔，它们不懂背叛，只知摇尾相迎。别让流浪的寒风刺痛它们的皮毛，别让饥饿的眼神黯淡星光。牵紧绳，给口暖食，多些耐心 ——
            你的小小善意，却是它们的整个世界。用爱灌溉，让每个毛茸茸的生命都能安稳入梦。
          </div>
        </div>
        <a href="#" class="read-more">READ MORE 阅读更多</a>
      </div>
    </div>

    <!-- 页脚 -->
    <Footer />
  </div>
</template>

<script setup>
import { UserFilled } from '@element-plus/icons-vue'
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue';
import CardGrid from '../../components/CardGrid.vue';
import Footer from '../../components/fonnter.vue';
import axios from 'axios';
import { useRouter } from 'vue-router';
import Cookies from 'js-cookie';

// 路由实例
const router = useRouter();

// 导航菜单状态
const isMenuVisible = ref(false);
const showDropdowns = ref({
  dog: false,
  cat: false,
  other: false,
  us: false
});

// 下拉菜单数据
const dropdownItems = {
  dog: {
    label: 'DOGS狗',
    subItems: [
      { label: 'Dog Adoption领养', route: '/adoptdog' },
      { label: 'Searching for dogs寻找', route: '/seachdog' },
      { label: 'Dog Adoption Articles文章', route: '/articlesdog' }
    ]
  },
  cat: {
    label: 'CATS猫',
    subItems: [
      { label: 'Cat Adoption领养', route: '/adoptcat' },
      { label: 'Searching for cats寻找', route: '/seachcat' },
      { label: 'Cat Adoption Articles文章', route: '/articlescat' }
    ]
  },
  other: {
    label: 'Other Pets其他宠物',
    subItems: [
      { label: 'Other Adoption领养', route: '/adoptother' },
      { label: 'Searching for other pets寻找', route: '/seachother' },
      { label: 'Other Adoption Articles文章', route: '/articlesother' }
    ]
  },
  us: {
    label: 'About US关于我们',
    subItems: [
      { label: 'Join Us加入我们', route: '/join' },
      { label: 'Charitable contribution慈善捐赠', route: '/donation' }
    ]
  }
};

// 搜索相关 - 添加搜索类型
const searchType = ref('post'); // 'post' 找贴, 'user' 找人
const searchQuery = ref('');
const searchResults = ref([]);

// 用户信息
const userInfo = ref({
  id: '', // 添加用户ID
  account: '',
  avatar: '',
  nickname: ''
});
const isLoggedIn = ref(false);
const isUserMenuVisible = ref(false);

// 聊天面板相关
const isChatPanelVisible = ref(false);
const friends = ref([]); // 初始化空数组，将从API获取数据
const filteredFriends = ref([]);
const friendSearchQuery = ref('');
const currentFriend = ref(null);
const newMessage = ref('');
const userAvatar = ref('https://picsum.photos/id/1000/200/200');
const messagesContainer = ref(null);

// 好友请求相关
const newFriendRequests = ref([]);
const hasNewFriendRequests = ref(false);
const isFriendRequestsVisible = ref(false);

// WebSocket相关
const websocket = ref(null);
const isWebSocketConnected = ref(false);
const statusText = ref('未连接');
const statusIcon = ref('fa fa-circle-o-notch fa-spin');
const statusClass = ref('bg-yellow-100 text-yellow-800 p-2 rounded text-sm flex items-center');

// 轮播图相关
const slides = [
  '/src/assets/images/CarouselImgs/2c22266c6b9dd4818382aa7b451df143.jpeg',
  '/src/assets/images/CarouselImgs/32d0d51efebf62bf8d927ad22bc82e65.jpeg',
  '/src/assets/images/CarouselImgs/7d23e2cbeef05ecf5260b643e9dffba9.jpeg',
  '/src/assets/images/CarouselImgs/7fb139407fee1e21e6d54fa058ad2a81.jpeg',
  '/src/assets/images/CarouselImgs/ac2d864ee9246f568dd7e38ac0db6c44.jpeg',
];
const extendedSlides = ref([...slides, slides[0]]);
let currentSlide = ref(0);
let slideInterval = null;
let isTransitioning = ref(false);

// 卡片数据
const cardsData = ref([
  { id: 1, image: '/src/assets/images/cat.png', name: 'Card One' },
  { id: 2, image: '/src/assets/images/cat.png', name: 'Card Two' },
  { id: 3, image: '/src/assets/images/cat.png', name: 'Card Three' },
  { id: 4, image: '/src/assets/images/cat.png', name: 'Card Four' }
]);

// 导航菜单方法
const toggleMenu = () => {
  isMenuVisible.value = !isMenuVisible.value;
};

const showDropdown = (key) => {
  showDropdowns.value[key] = true;
};

const hideDropdown = (key) => {
  showDropdowns.value[key] = false;
};

// 获取新的好友请求
const getNewFriendRequests = async () => {
  try {
    const token = Cookies.get('token');
    const response = await axios.get(
      'http://localhost:8080/Petrescue/users/getNewfriends',
      {
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        withCredentials: true
      }
    );

    if (response.data.success && response.data.code === 0) {
      newFriendRequests.value = response.data.data || [];
      // 如果有新请求，显示红点
      hasNewFriendRequests.value = newFriendRequests.value.length > 0;
    } else {
      console.error('获取新好友请求失败:', response.data.message);
    }
  } catch (error) {
    console.error('获取新好友请求出错:', error);
  }
};

// 切换好友请求面板显示
const toggleFriendRequests = async () => {
  // 如果是首次打开，获取最新的好友请求
  if (!isFriendRequestsVisible.value) {
    await getNewFriendRequests();
  }
  isFriendRequestsVisible.value = !isFriendRequestsVisible.value;
};

// 处理好友请求（接受或拒绝）
const handleFriendRequest = async (userId, accept) => {
  try {
    const token = Cookies.get('token');
    if (accept) {
      const response = await axios.get('http://localhost:8080/Petrescue/users/addFriend',
        {
          params: { friendId: userId },
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
          },
          withCredentials: true
        }
      );
      if (response.status === 200) {
        // 从列表中移除处理过的请求
        newFriendRequests.value = newFriendRequests.value.filter(request => request.id !== userId);
        hasNewFriendRequests.value = newFriendRequests.value.length > 0;

        // 如果接受了请求，刷新好友列表
        if (accept) {
          await getFriends();
        }

        alert(accept ? '已成功接受好友请求' : '已拒绝好友请求');
      } else {
        alert('操作失败: ' + (response.data.message || '未知错误'));
      }
    }

  } catch (error) {
    console.error('处理好友请求出错:', error);
    alert('处理好友请求时发生错误，请稍后重试');
  }
};

// 搜索方法 - 根据类型调用不同接口
const performSearch = async () => {
  try {
    const query = searchQuery.value.trim();
    if (!query) {
      alert('请输入搜索内容');
      return;
    }

    let response;
    // 根据搜索类型调用不同接口
    if (searchType.value === 'post') {
      // 找贴 - 调用博客接口
      response = await axios.post('http://localhost:8080/Petrescue/blog/Blogs', {
        dwType: 0,
        blogType: 0,
        search: query,
      });
    } else {
      // 找人 - 调用用户搜索接口
      response = await axios.get(`http://localhost:8080/Petrescue/users/selectUser?search=${encodeURIComponent(query)}`,
        {
          headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${Cookies.get('token')}`
          },
          withCredentials: true
        });
    }

    const { code, data, message } = response.data;

    if ((code === "200" || code === 0) && data) {
      searchResults.value = searchType.value === 'post' ? data.blogs : data;
      router.push({
        name: 'seach',
        query: {
          results: JSON.stringify(searchResults.value),
          searchQuery: query,
          searchType: searchType.value
        }
      });
    } else {
      if (!searchResults.value.length) {
        alert('没有找到匹配的结果');
      } else {
        alert(message || '搜索失败，请稍后重试');
      }
    }
  } catch (error) {
    console.error('搜索出错:', error);
    alert('搜索过程中出错，请检查网络连接后重试');
  }
};

// 获取好友列表
const getFriends = async () => {
  try {
    //获取token
    const token = Cookies.get('token');
    const response = await axios.get('http://localhost:8080/Petrescue/users/getfriends',
      {
        headers: {
          'Content-Type': 'application',
          'Authorization': `Bearer ${token}` // 添加token
        },
        withCredentials: true
      }
    );

    if (response.data.success && response.data.code === 0) {
      // 转换API返回的数据格式以适应我们的界面需求
      if (response.data.data) {
        const formattedFriends = response.data.data.map(friend => ({
          id: friend.id,
          name: friend.nickname,
          nickname: friend.nickname, // 保持一致性
          avatar: friend.avatar || 'https://picsum.photos/id/1005/200/200', // 提供默认头像
          account: friend.account,
          phone: friend.phone,
          lastMessage: '暂无消息', // 初始消息
          lastTime: '', // 初始时间
          unread: 0, // 初始未读消息数
          messages: [] // 初始消息列表
        }));

        friends.value = formattedFriends;
        filteredFriends.value = [...friends.value];
      }

    } else {
      console.error('获取好友列表失败:', response.data.message);
      alert('获取好友列表失败: ' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('获取好友列表出错:', error);
    alert('获取好友列表时发生错误，请稍后重试');
  }
};

// 删除好友
const deleteFriend = async (friendId) => {
  if (!confirm('确定要删除这个好友吗？')) {
    return;
  }

  try {
    const token = Cookies.get('token');
    const response = await axios.get(
      'http://localhost:8080/Petrescue/users/deleteFriend',
      {
        params: { friendId },
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        withCredentials: true
      }
    );

    if (response.data.success && response.data.code === 0) {
      // 如果删除的是当前正在聊天的好友，关闭聊天窗口
      if (currentFriend.value && currentFriend.value.id === friendId) {
        currentFriend.value = null;
      }

      // 从列表中移除该好友
      friends.value = friends.value.filter(friend => friend.id !== friendId);
      filteredFriends.value = filteredFriends.value.filter(friend => friend.id !== friendId);

      alert('成功删除好友');
    } else {
      alert('删除好友失败: ' + (response.data.message || '未知错误'));
    }
  } catch (error) {
    console.error('删除好友出错:', error);
    alert('删除好友时发生错误，请稍后重试');
  }
};

// 用户菜单方法
const toggleUserMenu = () => {
  isUserMenuVisible.value = !isUserMenuVisible.value;
};

// 点击其他区域关闭用户菜单
const closeUserMenuOnOutsideClick = (event) => {
  const userInfoEl = document.querySelector('.user-info');
  if (userInfoEl && !userInfoEl.contains(event.target)) {
    isUserMenuVisible.value = false;
  }
};

// 初始化WebSocket连接
const initWebSocket = () => {
  // 如果用户未登录或已经有连接，则不重新连接
  if (!isLoggedIn.value || (websocket.value && websocket.value.readyState !== WebSocket.CLOSED)) {
    return;
  }
  try {
    // 更新连接状态
    updateWebSocketStatus(false, '正在连接...', 'fa fa-circle-o-notch fa-spin', 'bg-yellow-100 text-yellow-800');
    // 连接WebSocket服务器
    const wsUri = `ws://localhost:8080/websocket/${userInfo.value.id}`;
    websocket.value = new WebSocket(wsUri);
    // 连接成功
    websocket.value.onopen = function () {
      updateWebSocketStatus(true, '已连接', 'fa fa-check-circle', 'bg-green-100 text-green-800');
      addSystemMessage('连接成功，可以开始聊天了');
    };
    // 接收消息
    websocket.value.onmessage = function (event) {
      const message = event.data;
      const colonIndex = message.indexOf(':');
      if (colonIndex > 0) {
        const senderId = parseInt(message.substring(0, colonIndex));
        const content = message.substring(colonIndex + 1);
        receiveMessage(senderId, content);
      } else {
        addSystemMessage(message);
      }
    };
    // 连接关闭
    websocket.value.onclose = function () {
      updateWebSocketStatus(false, '连接已关闭，正在重连...', 'fa fa-exclamation-triangle', 'bg-red-100 text-red-800');
      addSystemMessage('连接已关闭，正在尝试重连...');
      // 尝试重连
      setTimeout(initWebSocket, 3000);
    };
    // 连接错误
    websocket.value.onerror = function (error) {
      updateWebSocketStatus(false, '连接错误', 'fa fa-exclamation-circle', 'bg-red-100 text-red-800');
      addSystemMessage('连接发生错误，请检查网络');
      console.error('WebSocket错误:', error);
    };
  } catch (error) {
    console.error('初始化WebSocket失败:', error);
    updateWebSocketStatus(false, '连接失败', 'fa fa-exclamation-circle', 'bg-red-100 text-red-800');
  }
};

// 更新WebSocket状态
const updateWebSocketStatus = (connected, text, icon, className) => {
  isWebSocketConnected.value = connected;
  statusText.value = text;
  statusIcon.value = icon;
  statusClass.value = `${className} p-2 rounded text-sm flex items-center`;
};

// 添加系统消息
const addSystemMessage = (message) => {
  const now = new Date();
  const timeStr = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
  // 如果有当前聊天对象，添加到当前聊天
  if (currentFriend.value) {
    currentFriend.value.messages.push({
      text: message,
      time: timeStr,
      isUser: false,
      isSystem: true
    });
    scrollToBottom();
  } else {
    // 否则显示通知
    // alert(`系统消息: ${message}`);
  }
};

// 接收消息处理
const receiveMessage = (senderId, content) => {
  const now = new Date();
  const timeStr = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
  // 查找发送消息的好友
  const friendIndex = friends.value.findIndex(friend => friend.id === senderId);
  if (friendIndex !== -1) {
    friends.value[friendIndex].lastMessage = content;
    friends.value[friendIndex].lastTime = timeStr;
    if (!currentFriend.value || currentFriend.value.id !== senderId) {
      friends.value[friendIndex].unread++;
    }
    friends.value[friendIndex].messages.push({
      text: content,
      time: timeStr,
      isUser: false
    });
    if (currentFriend.value && currentFriend.value.id === senderId) {
      scrollToBottom();
    }
  } else {
    addSystemMessage(`${content}`);
  }
};

// 聊天面板方法 - 修改为点击时获取好友列表
const handleIconClick = async () => {
  // 显示聊天面板
  isChatPanelVisible.value = true;
  // 获取好友列表
  await getFriends();
  // 如果是首次打开且已登录，初始化WebSocket连接
  if (isLoggedIn.value && !isWebSocketConnected.value) {
    initWebSocket();
  }
};

const closeChatPanel = () => {
  isChatPanelVisible.value = false;
  isFriendRequestsVisible.value = false; // 关闭聊天面板时同时关闭好友请求面板
};

const selectFriend = async (friend) => {
  try {
    // 重置未读消息
    if (friend.unread > 0) {
      friend.unread = 0;
    }

    // 选中当前好友
    currentFriend.value = friend;

    // 调用接口获取历史消息
    const token = Cookies.get('token');
    const response = await axios.get(
      'http://localhost:8080/Petrescue/content/getcontent',
      {
        params: {
          receiveId: friend.id,  // 好友ID作为接收者ID
          isRead: true           // 标记为已读
        },
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        withCredentials: true
      }
    );

    if (response.data && response.data.data) {
      // 格式化历史消息并添加到当前好友的消息列表
      const formattedMessages = response.data.data.map(msg => {
        // 转换时间格式 (YYYY-MM-DDTHH:mm:ss -> HH:mm)
        const date = new Date(msg.createTime);
        const timeStr = `${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;

        return {
          text: msg.content,
          time: timeStr,
          // 判断是否为当前用户发送的消息
          isUser: msg.sendId === userInfo.value.id
        };
      });

      // 清空现有消息并添加历史消息
      currentFriend.value.messages = formattedMessages;

      // 滚动到最新消息
      scrollToBottom();
    }
  } catch (error) {
    console.error('获取聊天历史失败:', error);
    addSystemMessage('获取历史消息失败，请重试');
  }
};

const filterFriends = () => {
  const query = friendSearchQuery.value.toLowerCase();
  filteredFriends.value = friends.value.filter(friend =>
    friend.name.toLowerCase().includes(query) ||
    (friend.lastMessage && friend.lastMessage.toLowerCase().includes(query))
  );
};

const sendMessage = () => {
  if (!currentFriend.value || !newMessage.value.trim() || !isWebSocketConnected.value) return;

  const now = new Date();
  const timeStr = `${now.getHours()}:${now.getMinutes().toString().padStart(2, '0')}`;
  const messageText = newMessage.value.trim();

  try {
    // 按照后端要求的格式发送: 接收ID:消息内容
    websocket.value.send(`${currentFriend.value.id}:${messageText}`);

    // 添加用户消息到本地列表
    currentFriend.value.messages.push({
      text: messageText,
      time: timeStr,
      isUser: true
    });

    // 更新最后一条消息和时间
    currentFriend.value.lastMessage = messageText;
    currentFriend.value.lastTime = timeStr;

    newMessage.value = '';
    scrollToBottom();
  } catch (error) {
    console.error('发送消息失败:', error);
    addSystemMessage('发送消息失败，请重试');
  }
};

// 滚动到最新消息
const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
    }
  });
};

// 退出登录
const handleLogout = () => {
  // 关闭WebSocket连接
  if (websocket.value) {
    websocket.value.close();
  }

  // 清除sessionStorage中的用户信息
  sessionStorage.removeItem('user');

  // 关键：清除Cookie中的token
  Cookies.remove('token'); // 移除名为token的Cookie

  // 跳转到登录页
  router.push({ name: 'login' });
};

// 轮播图方法
const startSlideshow = () => {
  stopSlideshow(); // 先停止已有定时器
  slideInterval = setInterval(() => {
    if (!isTransitioning.value) {
      nextSlide();
    }
  }, 4000);
};

const stopSlideshow = () => {
  if (slideInterval) {
    clearInterval(slideInterval);
    slideInterval = null;
  }
};

const nextSlide = () => {
  isTransitioning.value = true;
  currentSlide.value++;
};

const handleTransitionEnd = () => {
  // 当到达最后一张（实际上是第一张的副本）时
  if (currentSlide.value === slides.length) {
    // 禁用过渡效果，瞬间跳转到第一张
    const carouselInner = document.querySelector('.carousel-inner');
    carouselInner.style.transition = 'none';
    currentSlide.value = 0;

    // 强制重绘，确保跳转生效
    void carouselInner.offsetWidth;

    // 恢复过渡效果
    carouselInner.style.transition = 'transform 0.5s ease-in-out';
  }
  isTransitioning.value = false;
};

// 监听登录状态变化，初始化WebSocket
watch(isLoggedIn, (newVal) => {
  if (newVal) {
    initWebSocket();
    getNewFriendRequests(); // 登录状态变化时获取好友请求
  } else if (websocket.value) {
    websocket.value.close();
  }
});

// 生命周期钩子
onMounted(() => {
  // 启动轮播
  startSlideshow();

  // 加载用户信息
  const storedUser = sessionStorage.getItem('user');
  if (storedUser) {
    const userData = JSON.parse(storedUser);
    userInfo.value = {
      id: userData.id || '', // 确保获取用户ID
      account: userData.account || '',
      avatar: userData.avatar || '',
      nickname: userData.nickname || ''
    };
    isLoggedIn.value = true;
    userAvatar.value = userData.avatar || 'https://picsum.photos/id/1000/200/200';
    getNewFriendRequests();
  }

  // 添加点击事件监听器
  document.addEventListener('click', closeUserMenuOnOutsideClick);
});

onUnmounted(() => {
  // 清理定时器
  stopSlideshow();

  // 移除事件监听器
  document.removeEventListener('click', closeUserMenuOnOutsideClick);

  // 关闭WebSocket连接
  if (websocket.value) {
    websocket.value.close();
  }
});
</script>

<style lang="less" scoped>
/* 样式内容保持不变，新增好友请求相关样式 */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body,
html {
  height: 100%;
  width: 100%;
  font-family: Arial, sans-serif;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
}

#app {
  width: 100%;
  min-height: 100%;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

/* 头部样式 */
.header {
  width: 100%;
  background: linear-gradient(135deg, #fff9f0 0%, #fef3c7 100%);
  padding: 12px 0;
  position: relative;
  box-shadow: 0 2px 10px rgba(124, 45, 18, 0.1);
  border-bottom: 1px solid rgba(234, 88, 12, 0.2);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .logo-container {
    margin-left: 60px;

    .logo {
      width: 60px;
      height: 60px;
      object-fit: contain;
    }
  }

  .dropdown-container {
    position: relative;
    margin-left: 120px;
    flex-grow: 1;

    .main-nav {
      display: flex;
      align-items: center;
      gap: 20px;
      list-style: none;
      padding: 0;
      margin: 0;

      .menu-item {
        color: #7c2d12;
        font-weight: 500;
        cursor: pointer;
        display: flex;
        align-items: center;
        padding: 8px 12px;
        border-radius: 6px;
        transition: all 0.3s ease;

        &:hover {
          background-color: rgba(234, 88, 12, 0.1);
          color: #c2410c;
        }

        .arrow {
          margin-left: 6px;
          transition: transform 0.3s ease;

          &.rotate {
            transform: rotate(180deg);
          }
        }
      }

      .search-item {
        display: flex;
        align-items: center;

        /* 搜索类型选择器样式 */
        .search-type-selector {
          display: flex;
          background-color: rgba(254, 243, 199, 0.7);
          border: 1px solid #f59e0b;
          border-radius: 20px 0 0 20px;
          overflow: hidden;

          span {
            padding: 8px 15px;
            color: #7c2d12;
            cursor: pointer;
            transition: all 0.2s ease;

            &.active {
              background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
              color: white;
            }

            &:first-child {
              border-right: 1px solid #f59e0b;
            }
          }
        }

        input {
          padding: 8px 15px;
          border: 1px solid #f59e0b;
          border-left: none;
          /* 与选择器合并边框 */
          border-radius: 0 20px 20px 0;
          background-color: rgba(254, 243, 199, 0.7);
          color: #7c2d12;
          width: 200px;
          transition: all 0.3s ease;

          &:focus {
            outline: none;
            border-color: #ea580c;
            box-shadow: 0 0 0 2px rgba(234, 88, 12, 0.2);
            width: 250px;
          }

          &::placeholder {
            color: #d97706;
            opacity: 0.7;
          }
        }

        button {
          padding: 8px 15px;
          background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
          color: white;
          border: none;
          border-radius: 20px;
          cursor: pointer;
          transition: all 0.2s ease;

          &:hover {
            background: linear-gradient(90deg, #c2410c 0%, #9a3412 100%);
            transform: translateY(-1px);
          }
        }
      }
    }

    .dropdown-wrapper {
      position: absolute;
      top: 100%;
      left: 0;
      z-index: 100;
    }

    .dropdown-menu {
      height: 50px;
      background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
      border-radius: 0 0 8px 8px;
      list-style: none;
      padding: 0;
      margin: 0;
      display: flex;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      overflow: hidden;

      li {
        padding: 12px 20px;
        position: relative;
        cursor: pointer;

        a {
          color: white;
          text-decoration: none;
          font-weight: 500;
          display: block;
          transition: all 0.2s ease;

          &:hover {
            color: #fef3c7;
          }
        }

        &:not(:last-child)::after {
          content: "";
          position: absolute;
          right: 0;
          top: 50%;
          transform: translateY(-50%);
          height: 60%;
          width: 1px;
          background-color: rgba(255, 255, 255, 0.3);
        }
      }
    }

    .submenu {
      background-color: #9a3412;
      border-radius: 0 0 8px 8px;
      list-style: none;
      padding: 8px 0;
      margin: 0;
      z-index: 100;
      box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
      display: none;
      position: absolute;
      top: 50px;

      &.show {
        display: block;
      }

      li {
        padding: 8px 20px;

        .menu-link {
          color: #fef3c7;
          text-decoration: none;
          display: block;
          transition: all 0.2s ease;
          padding: 6px 0;

          &:hover {
            color: white;
            background-color: rgba(234, 88, 12, 0.3);
            border-radius: 4px;
          }
        }
      }
    }

    .dog {
      &+.submenu {
        left: 0;
      }
    }

    .cat {
      &+.submenu {
        left: 120px;
      }
    }

    .other {
      &+.submenu {
        left: 240px;
      }
    }

    .us {
      &+.submenu {
        left: 400px;
      }
    }
  }

  .user-area {
    display: flex;
    align-items: center;
    gap: 12px;
    position: relative;
    margin-right: 20px;

    .avatar-icon-container {
      margin-right: 10px;
      display: flex;
      align-items: center;
      cursor: pointer;

      .el-icon {
        transition: all 0.3s ease;

        &:hover {
          color: #c2410c !important;
          transform: scale(1.1);
        }
      }
    }

    .user-info {
      display: flex;
      align-items: center;
      gap: 12px;
      position: relative;

      .avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        border: 2px solid rgba(234, 88, 12, 0.3);

        img {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .user-name {
        display: flex;
        align-items: center;
        gap: 4px;
        cursor: pointer;
        color: #7c2d12;
        font-weight: 500;

        .dropdown-arrow {
          color: #9a3412;
          transition: transform 0.3s ease;
        }
      }

      .user-menu {
        position: absolute;
        top: 100%;
        right: 0;
        background-color: #fff9f0;
        border: 1px solid rgba(234, 88, 12, 0.3);
        border-radius: 8px;
        padding: 8px 0;
        list-style: none;
        min-width: 160px;
        box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        display: none;
        z-index: 100;

        &.show {
          display: block;
          animation: fadeIn 0.2s ease;
        }

        li {
          padding: 8px 16px;

          a {
            color: #7c2d12;
            text-decoration: none;
            display: block;
            transition: all 0.2s ease;

            &:hover {
              color: #ea580c;
              background-color: rgba(234, 88, 12, 0.1);
            }
          }
        }
      }
    }

    .post-button {
      margin-right: 20px;

      button {
        padding: 8px 16px;
        background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
        color: white;
        border: none;
        border-radius: 20px;
        cursor: pointer;
        transition: all 0.2s ease;

        &:hover {
          background: linear-gradient(90deg, #c2410c 0%, #9a3412 100%);
          transform: translateY(-1px);
        }

        a {
          color: white;
          text-decoration: none;
        }
      }
    }
  }
}

/* 聊天面板样式 - 更新为主题橙色系 */
.chat-panel-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.chat-panel {
  width: 800px;
  height: 600px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(124, 45, 18, 0.3);
  display: flex;
  flex-direction: column;
  overflow: hidden;
  transform: translateY(0);
  animation: slideUp 0.3s ease;
}

.chat-header {
  background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
  color: white;
  padding: 12px 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);

  .header-left {
    display: flex;
    align-items: center;
    gap: 15px;

    .back-icon {
      cursor: pointer;
      font-size: 18px;
      padding: 4px;
      transition: background-color 0.2s;

      &:hover {
        background-color: rgba(255, 255, 255, 0.2);
        border-radius: 4px;
      }
    }

    .header-title {
      font-size: 16px;
      font-weight: 500;
    }

    // 好友请求按钮样式
    .friend-request-btn {
      background-color: rgba(255, 255, 255, 0.2);
      color: white;
      border: none;
      padding: 5px 12px;
      border-radius: 15px;
      cursor: pointer;
      font-size: 14px;
      display: flex;
      align-items: center;
      gap: 5px;
      transition: all 0.2s ease;

      &:hover {
        background-color: rgba(255, 255, 255, 0.3);
      }

      &.has-requests {
        background-color: #ff6b35;
      }

      .request-count {
        background-color: white;
        color: #ea580c;
        border-radius: 10px;
        padding: 0 6px;
        font-size: 12px;
        font-weight: bold;
      }
    }
  }

  .status-indicator {
    margin-left: auto;
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 4px;
  }
}

// 好友请求面板样式
.friend-requests-panel {
  width: 100%;
  height: calc(100% - 50px);
  background-color: #fff9f0;
  display: flex;
  flex-direction: column;

  .requests-header {
    padding: 15px 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid rgba(234, 88, 12, 0.2);

    h3 {
      color: #7c2d12;
      font-size: 16px;
      font-weight: 600;
    }

    .close-btn {
      background: none;
      border: none;
      color: #9a3412;
      font-size: 18px;
      cursor: pointer;
      width: 30px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: center;
      border-radius: 50%;
      transition: all 0.2s ease;

      &:hover {
        background-color: rgba(234, 88, 12, 0.1);
        color: #ea580c;
      }
    }
  }

  .requests-list {
    flex: 1;
    overflow-y: auto;
    padding: 10px;
  }

  .request-item {
    display: flex;
    align-items: center;
    padding: 12px 15px;
    background-color: white;
    border-radius: 8px;
    margin-bottom: 10px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
    transition: transform 0.2s ease;

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 3px 6px rgba(234, 88, 12, 0.1);
    }

    .request-avatar {
      width: 50px;
      height: 50px;
      border-radius: 50%;
      overflow: hidden;
      margin-right: 15px;
      border: 2px solid rgba(234, 88, 12, 0.2);

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .request-info {
      flex: 1;

      .request-name {
        font-size: 16px;
        font-weight: 500;
        color: #7c2d12;
        margin-bottom: 4px;
      }

      .request-account,
      .request-phone {
        font-size: 13px;
        color: #9a3412;
        opacity: 0.8;
        margin-bottom: 2px;
      }
    }

    .request-actions {
      display: flex;
      gap: 10px;

      button {
        padding: 6px 12px;
        border-radius: 4px;
        font-size: 14px;
        cursor: pointer;
        transition: all 0.2s ease;
        border: none;
      }

      .accept-btn {
        background-color: #10b981;
        color: white;

        &:hover {
          background-color: #059669;
        }
      }

      .reject-btn {
        background-color: #ef4444;
        color: white;

        &:hover {
          background-color: #dc2626;
        }
      }
    }
  }

  .no-requests {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #d97706;
    font-size: 16px;
    padding: 20px;
    text-align: center;
  }
}

.chat-main {
  display: flex;
  flex: 1;
  overflow: hidden;
}

/* 左侧好友列表 */
.friend-list {
  width: 280px;
  background-color: #fff9f0;
  border-right: 1px solid rgba(234, 88, 12, 0.2);
  display: flex;
  flex-direction: column;

  .search-box {
    padding: 12px;
    border-bottom: 1px solid rgba(234, 88, 12, 0.2);

    .search-input {
      width: 100%;
      padding: 8px 12px;
      background-color: rgba(254, 243, 199, 0.5);
      border: 1px solid #f59e0b;
      border-radius: 4px;
      color: #7c2d12;
      font-size: 14px;
      transition: all 0.2s;

      &::placeholder {
        color: #d97706;
        opacity: 0.7;
      }

      &:focus {
        outline: none;
        border-color: #ea580c;
        background-color: rgba(254, 243, 199, 0.8);
      }
    }
  }

  .friend-items {
    flex: 1;
    overflow-y: auto;

    .friend-item {
      display: flex;
      align-items: center;
      padding: 12px;
      cursor: pointer;
      border-bottom: 1px solid rgba(234, 88, 12, 0.1);
      transition: background-color 0.2s;
      position: relative;

      &:hover {
        background-color: rgba(254, 243, 199, 0.5);
      }

      &.active {
        background-color: rgba(234, 88, 12, 0.1);
        border-left: 3px solid #ea580c;
      }

      .friend-avatar {
        position: relative;
        margin-right: 12px;

        img {
          width: 45px;
          height: 45px;
          border-radius: 4px;
          object-fit: cover;
        }

        .unread-badge {
          position: absolute;
          top: -4px;
          right: -4px;
          background-color: #ea580c;
          color: white;
          border-radius: 10px;
          min-width: 18px;
          height: 18px;
          font-size: 12px;
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 0 4px;
        }
      }

      .friend-info {
        flex: 1;

        .friend-name {
          color: #7c2d12;
          font-size: 14px;
          font-weight: 500;
          margin-bottom: 4px;
        }

        .friend-last-message {
          color: #9a3412;
          font-size: 12px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          max-width: 150px;
        }
      }

      .friend-time {
        color: #d97706;
        font-size: 11px;
        margin-right: 8px;
      }

      /* 删除好友按钮样式 */
      .delete-friend-btn {
        background-color: transparent;
        border: none;
        color: #9a3412;
        cursor: pointer;
        padding: 4px;
        opacity: 0;
        transition: all 0.2s ease;
        border-radius: 4px;

        &:hover {
          background-color: rgba(234, 88, 12, 0.1);
          color: #ea580c;
        }
      }

      /* 鼠标悬停时显示删除按钮 */
      &:hover .delete-friend-btn {
        opacity: 1;
      }
    }
  }
}

/* 右侧聊天内容 */
.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  background-color: #fefbf5;

  .chat-header-info {
    background-color: #fff9f0;
    padding: 12px 16px;
    border-bottom: 1px solid rgba(234, 88, 12, 0.2);

    .current-friend {
      .friend-name {
        font-size: 16px;
        font-weight: 500;
        color: #7c2d12;
      }
    }
  }

  .chat-messages {
    flex: 1;
    padding: 16px;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
    gap: 16px;

    .message-item {
      display: flex;
      gap: 8px;
      max-width: 70%;

      &.user-message {
        align-self: flex-end;
        flex-direction: row-reverse;

        .message-content {
          background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
          color: white;

          .message-text {
            color: white;
          }

          .message-time {
            color: rgba(255, 255, 255, 0.7);
          }
        }
      }

      &.friend-message {
        align-self: flex-start;

        .message-content {
          background-color: white;
          border: 1px solid rgba(234, 88, 12, 0.2);
        }
      }

      &.system-message {
        align-self: center;

        .message-content {
          background-color: #fef3c7;
          border: 1px solid #f59e0b;
          color: #7c2d12;
        }
      }

      .message-avatar {
        img {
          width: 36px;
          height: 36px;
          border-radius: 4px;
          object-fit: cover;
        }
      }

      .message-content {
        padding: 8px 12px;
        border-radius: 8px;
        box-shadow: 0 1px 3px rgba(124, 45, 18, 0.1);

        .message-text {
          font-size: 14px;
          line-height: 1.4;
          color: #7c2d12;
          margin-bottom: 4px;
        }

        .message-time {
          font-size: 11px;
          color: #d97706;
          text-align: right;
        }
      }
    }
  }

  .chat-input-area {
    background-color: #fff9f0;
    border-top: 1px solid rgba(234, 88, 12, 0.2);
    padding: 12px 16px;

    .input-box {
      display: flex;
      gap: 8px;
      align-items: flex-end;

      textarea {
        flex: 1;
        padding: 8px 12px;
        border: 1px solid #f59e0b;
        border-radius: 4px;
        resize: none;
        font-size: 14px;
        font-family: inherit;
        background-color: rgba(255, 255, 255, 0.8);
        color: #7c2d12;
        transition: all 0.2s;

        &:focus {
          outline: none;
          border-color: #ea580c;
          box-shadow: 0 0 0 2px rgba(234, 88, 12, 0.1);
        }

        &::placeholder {
          color: #d97706;
          opacity: 0.7;
        }
      }

      .send-btn {
        background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
        color: white;
        border: none;
        padding: 8px 16px;
        border-radius: 4px;
        cursor: pointer;
        font-size: 14px;
        transition: all 0.2s;

        &:hover {
          background: linear-gradient(90deg, #c2410c 0%, #9a3412 100%);
          transform: translateY(-1px);
        }

        &:disabled {
          background-color: #f59e0b;
          opacity: 0.5;
          cursor: not-allowed;
        }
      }
    }
  }
}

.no-selection {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #d97706;
  font-size: 16px;
  background-color: #fefbf5;
}

/* 滚动条样式 */
.friend-items::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar,
.requests-list::-webkit-scrollbar {
  width: 4px;
}

.friend-items::-webkit-scrollbar-track,
.requests-list::-webkit-scrollbar-track {
  background: #fff9f0;
}

.friend-items::-webkit-scrollbar-thumb,
.requests-list::-webkit-scrollbar-thumb {
  background: #f59e0b;
  border-radius: 2px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #fefbf5;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #f59e0b;
  border-radius: 2px;
}

/* 轮播图样式 */
.carousel {
  position: relative;
  width: 100%;
  height: 467px;
  overflow: hidden;

  .carousel-inner {
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    transition: transform 0.5s ease-in-out;
  }

  .carousel-item {
    min-width: 100%;
    height: 100%;
    flex-shrink: 0;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }

  .carousel-caption {
    color: #ffffff;
    text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.5);
    position: absolute;
    top: 189px;
    left: 263px;
    text-align: center;

    h1 {
      font-size: 37px;
      margin-bottom: 10px;
      animation: fadeInUp 1s ease;
    }

    p {
      font-size: 22px;
      animation: fadeInUp 1.2s ease;
    }
  }
}

.divider {
  background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
  height: 15px;
  width: 100%;
}

/* 信息图标区 */
.info-icons {
  width: 100%;
  height: 156px;
  display: flex;
  justify-content: center;
  position: relative;
  z-index: 50;
  padding: 0 20px;

  .icon-item {
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    background-color: rgba(254, 243, 199, 0.7);
    border: 1px solid #f59e0b;
    width: 13%;
    height: 137px;
    margin-right: 50px;
    border-radius: 10px;
    cursor: pointer;
    transition: all 0.3s ease;

    &:last-child {
      margin-right: 0;
    }

    &:hover {
      border-color: #ea580c;
      box-shadow: 0 4px 6px rgba(234, 88, 12, 0.1);
      transform: translateY(-5px);
    }

    &.p-1 {
      background-image: url("../../assets/images/homeImgs/d82463d8092ae591f38b59682ce82074.png");
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
    }

    &.p-2 {
      background-image: url("../../assets/images/homeImgs/b3735a62351baffb6eb4687482b4d6f0.jpeg");
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
    }

    &.p-3 {
      background-image: url("../../assets/images/homeImgs/78001cf24b64e3ad0efc6c98c950256d.jpg");
      background-repeat: no-repeat;
      background-position: center;
      background-size: contain;
    }
  }
}

/* 宠物卡片区 */
.card-section {
  margin-top: 50px;
  padding: 0 20px 50px 20px;

  .section-title {
    width: 100%;
    color: #7c2d12;
    text-align: center;
    margin-bottom: 30px;

    h1 {
      font-size: 37px;
      margin-bottom: 10px;
    }

    h2 {
      letter-spacing: 5px;
      font-size: 22px;
      color: #9a3412;
    }
  }

  .card-container {
    padding: 30px 10px;
    width: 100%;
    min-height: 600px;
    border: 1px solid #f59e0b;
    background-color: rgba(254, 243, 199, 0.3);
    overflow: auto;
  }
}

/* 优化后的文章区域样式 */
.articles-section {
  margin: 50px auto 80px;
  width: 90%;
  max-width: 1200px;
  height: auto;
  min-height: 430px;
  padding: 0;
  display: flex;
  gap: 30px;
}

.article-card {
  flex: 1;
  height: 480px;
  margin: 0;
  background-color: white;
  border: 1px solid rgba(234, 88, 12, 0.2);
  border-radius: 12px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.05);
  transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  overflow: hidden;
  position: relative;

  &:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 20px rgba(234, 88, 12, 0.1);
    border-color: rgba(234, 88, 12, 0.3);
  }

  .article-image {
    width: 100%;
    height: calc(100% - 50px);
    background-size: cover;
    background-position: center;
    position: relative;
    overflow: hidden;

    &::before {
      content: "";
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background: linear-gradient(to bottom,
          rgba(0, 0, 0, 0.1) 0%,
          rgba(0, 0, 0, 0.7) 100%);
      z-index: 1;
      transition: all 0.3s ease;
    }

    .article-text {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 30px 25px 25px;
      color: white;
      font-size: 15px;
      line-height: 1.7;
      z-index: 2;
      text-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
      transform: translateY(10px);
      transition: all 0.3s ease;
    }
  }

  &:hover .article-image .article-text {
    transform: translateY(0);
  }

  .read-more {
    display: block;
    width: 100%;
    height: 50px;
    line-height: 50px;
    color: #7c2d12;
    font-size: 14px;
    text-align: center;
    background-color: #fff9f0;
    border-top: 1px solid rgba(234, 88, 12, 0.1);
    font-weight: 600;
    text-decoration: none;
    transition: all 0.3s ease;
    letter-spacing: 0.5px;

    &:hover {
      color: white;
      background: linear-gradient(90deg, #ea580c 0%, #c2410c 100%);
      border-top-color: transparent;
    }
  }

  // 为不同文章设置背景图片
  &.dog-article .article-image {
    background-image: url("../../assets/images/loginImgs/cat.jpg");
  }

  &.cat-article .article-image {
    background-image: url("../../assets/images/loginImgs/dog.jpg");
  }
}

/* 动画效果 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    transform: translateY(20px);
    opacity: 0;
  }

  to {
    transform: translateY(0);
    opacity: 1;
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 链接样式 */
.menu-link {
  color: #fef3c7;
  text-decoration: none;

  &.router-link-exact-active {
    color: white;
  }

  &:hover {
    color: white;
    background-color: rgba(234, 88, 12, 0.3);
  }
}

/* 通知红点样式 */
.avatar-icon-container {
  position: relative;

  .notification-badge {
    position: absolute;
    top: -5px;
    right: -5px;
    color: #ea580c;
    font-size: 16px;
    text-shadow: 0 0 2px rgba(255, 255, 255, 0.8);
    animation: pulse 2s infinite;
  }
}

/* 红点闪烁动画 */
@keyframes pulse {
  0% {
    opacity: 1;
    transform: scale(1);
  }

  50% {
    opacity: 0.7;
    transform: scale(1.2);
  }

  100% {
    opacity: 1;
    transform: scale(1);
  }
}
</style>
